<template>

    <div class="files-select" :class="{ active: selected.length > 0, fixed: fixed }">

        <div class="files-select-fixed">
            <cite>
                <slot></slot>
                <blockquote>
                    <em v-if="selected.length > 1" v-text="selected.length + ' Pictures Selected'"></em>
                    <em v-else v-text="selected.length + ' Picture Selected'"></em>
                    <button @click="moveto = true">Move</button>
                    <button @click="doDownload()">Download</button>
                    <button @click="remove = true">Delete</button>
                </blockquote>
            </cite>
        </div>

        <!-- 删除 -->
        <UxDialog :visible="remove" @close="remove = null">
            <div class="dialog-remove">
                <img src="@/assets/images/files/dialog-image-del.png" alt="">
                <p>Deleted images cannot be retrieved. Are you sure you want to delete this image?</p>
                <button type="primary" @click="doRemove()">Confirm</button>
                <UxLoading2 :loading="loading" />
            </div>
        </UxDialog>

        <!-- 移动到文件夹 -->
        <UxDialog key="moveto" :visible="moveto" @close="moveto = false">
            <div class="dialog-move">
                <h3>Select folder to locate the files</h3>
                <ul>
                    <li v-for="item in folders" :key="item.id" :class="{ active: folder_select == item.id }"
                        @click="folder_select = item.id">
                        <svg-icon name="user-files-folder-list" />
                        <span v-text="item.folder_name"></span>
                    </li>
                    <li @click="folder = {}">
                        <svg-icon name="user-files-folder-add" />
                        <span>New folder</span>
                    </li>
                </ul>
                <button @click="doMoveto()" type="primary">OK</button>
                <UxLoading2 :loading="loading" />
            </div>
        </UxDialog>

        <!-- 添加、编辑文件夹 -->
        <MaterialsFolderEditor key="editor" v-model="folder" @success="getFolders()" @close="folder = null" />

        <!-- 下载进度弹窗 -->
        <UxDialog :visible="!!downloading" :can-close="false" class="detail-downloading">
            <el-progress type="circle" color="#ea4c89" :percentage="downloading" :width="96"></el-progress>
            <p>Downloading</p>
        </UxDialog>

    </div>

</template>
<script>
import JSZip from "jszip";
import FileSaver from "file-saver";

export default {
    props: {
        list: { type: Array, default: () => [] },
        selected: { type: Array, default: () => [] },
        folders: { type: Array, default: () => [] },
    },
    data () {
        return {
            loading: false,
            remove: false,
            moveto: false,
            folder: null,
            downloading: 0,
            top: 100,
            fixed: false,
            folder_select: null,
        };
    },

    methods: {

        // 下载
        async doDownload () {

            // 制作压缩包
            var zip = new JSZip();
            let name = "download-" + new Date().getTime() + ".zip";

            // 进度
            const percent = {
                total: 0, // 至少有一步
                count: 0,
                timer: null,
                value: 0,
            }

            // 设置进度
            const setPercent = (init) => {

                if (!init) {
                    percent.count += 1;
                    percent.value = Math.max(1, Math.min(100, parseInt(100 * (percent.count / percent.total))));
                    this.downloading = percent.value

                } else {
                    //
                }

                let value = Math.max(1, Math.min(99, parseInt(100 * ((percent.count + 1) / percent.total))))

                if (percent.value >= value) {
                    percent.timer && clearTimeout(percent.timer);
                } else {
                    const time = parseInt(Math.random() * 1000)
                    percent.value += 1;
                    percent.timer && clearTimeout(percent.timer);
                    percent.timer = setTimeout(e => setPercent(true), time)
                    this.downloading = percent.value;
                }
            }

            let promises = [];
            // 获取 blob
            let getImageBlob = (item) => {
                return new Promise((resolve, reject) => {
                    var xhr = new XMLHttpRequest();
                    xhr.open("get", item.url, true);
                    xhr.responseType = "blob";
                    xhr.onload = function () {
                        if (this.status == 200) {
                            // item.blob = this.response;
                            zip.file(item.name, this.response);
                            setPercent();
                            resolve(item);
                        }
                    };
                    xhr.onerror = () => reject()
                    xhr.send();
                });
            };

            this.selected.map((id) => {
                const item = this.list.find(i => i.id == id)
                if (item) {
                    promises.push(getImageBlob({
                        url: this.$getImageUrl(item.img_url, "original"),
                        name: item.img_name,
                        blob: null,
                    }));
                }
            });

            percent.total = promises.length;
            percent.value = 1;
            this.downloading = percent.value;
            setPercent(true);

            Promise.all(promises).then(res => zip.generateAsync({ type: "blob" })).then((content) => {
                FileSaver(content, name);
                this.downloading = 0;
                this.$uxMessage.success("File downloaded");
                this.$emit('update:selected', []);

            }).catch((error) => {
                console.log(error);
                this.$uxMessage.warning("Failed to download image");
            });
        },
        // 删除
        async doRemove () {
            let req = { material_id: this.selected.join("|") };

            this.loading = true;
            let res = await this.$http("Material.delMaterial", req);

            if (res.code === 0) {
                this.loading = false;
                this.remove = null;
                this.$emit("reload");
                this.$uxMessage.success("Image deleted successfully");
            } else {
                this.loading = false;
                this.$uxMessage.warning("Failed to delete image");
            }
        },

        // 移动到文件夹
        async doMoveto () {
            if (!this.folder_select) {
                // 没有名字，不能提交
            } else {
                let ids = this.selected
                let req = {
                    folder_id: this.folder_select,
                    material_id: ids.join("|"),
                };

                this.loading = true;
                let res = await this.$http("Material.putMaterialFileToFolder", req);

                if (res.code === 0) {
                    this.loading = false;
                    this.folder = false;
                    this.moveto = false;
                    this.$emit('update:selected', []);
                    this.$emit("reload");
                    this.$uxMessage.success("Image moved successfully");
                } else {
                    this.loading = false;
                    this.$uxMessage.warning("Failed to move image");
                }
            }
        },

        async getFolders () {
            if (this.$parent.getFolders) {
                this.loading = true;
                await this.$parent.getFolders()
                this.loading = false;
            }
        },
        resize () {
            // const rect = this.$el.getBoundingClientRect()
            this.top = this.$el.offsetTop
        },
        checkHeaderActive () {
            const scrollY = document.documentElement.scrollTop || document.body.scrollTop
            this.fixed = scrollY >= this.top - 28
        },

    },
    mounted () {
        this.resize()
        this.checkHeaderActive();
        window.addEventListener('scroll', this.checkHeaderActive)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.checkHeaderActive)
    }
};
</script>

<style lang="scss" scoped>
.files-select {
    height: 18px;
    position: relative;

    .files-select-fixed {
        position: absolute;
        left: 0;
        top: 50%;
        margin-top: -26px;
        width: 100%;
        height: 52px;
        font-size: 16px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        display: flex;
        align-items: center;

        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            box-sizing: border-box;
            background-color: #fff;
            border-top: 1px solid #f5f5f5;
            border-bottom: 1px solid #ebebeb;
            // box-shadow: 0px 6px 6px 0px rgba(0, 0, 0, 0.06);
            transition: all 0.5s;
            opacity: 0;
        }

        cite {
            position: relative;
            width: 100%;
            margin: 0 auto;
            display: flex;
            box-sizing: border-box;
            padding-right: 460px;
            max-width: 1080px;
        }
    }

    blockquote {
        position: absolute;
        right: 0;
        margin: 0;
        top: 50%;
        transform: translateY(-50%);
        display: flex;
        align-items: center;
        transition: all 0.2s;
        opacity: 0;
        pointer-events: none;

        em {
            cursor: default;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
            line-height: 18px;
            margin-right: 4px;
        }

        button {
            width: 90px;
            height: 28px;
            background: #ffffff;
            border-radius: 6px;
            margin-left: 6px;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
        }
    }

    &.active blockquote {
        opacity: 1;
        pointer-events: all;
    }

    &.fixed.active .files-select-fixed {
        position: fixed;
        left: 228px;
        top: 59px;
        padding-left: 24px;
        padding-right: 24px;
        margin-top: 0;
        width: calc(100vw - 228px);
        box-sizing: border-box;
        z-index: 9;

        &::before {
            opacity: 1;
        }
    }
}

.dialog-remove {
    width: 320px;
    height: 414px;
    box-sizing: border-box;
    padding: 60px 14px 14px;
    display: flex;
    flex-direction: column;
    align-items: center;

    &>img {
        width: 80px;
        height: 80px;
    }

    p {
        flex: 1;
        display: flex;
        margin: 0 4px;
        align-items: center;
        justify-content: center;
        text-align: center;
        font-size: 16px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;
        line-height: 22px;
    }

    &>button {
        margin-top: 56px;
        width: 100%;
        height: 38px;
        min-height: 38px;
    }
}

.dialog-move {
    width: 320px;
    height: calc(100vh - 80px);
    min-height: 414px;
    max-height: 480px;
    padding: 22px 0 0;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;

    &>h3 {
        margin: 0 14px;
        font-size: 14px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 20px;
        margin-bottom: 12px;
        text-align: center;
    }

    ul {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: auto;
        padding: 0 14px 5px;
        border-bottom: 1px solid #e6e6e6;

        li {
            margin: 5px 0;
            height: 32px;
            min-height: 32px;
            padding: 0 8px;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            cursor: pointer;
            height: 36px;
            background: #ffffff;
            border-radius: 6px;
            border: 1px solid #e6e6e6;
            color: #555555;

            span {
                overflow: hidden;
                text-overflow: ellipsis;
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                line-height: 16px;
                flex: 1;
            }

            svg {
                width: 16px;
                height: 16px;
                margin-right: 8px;
            }

            &:hover {
                background: #f6f6f6;
            }

            &:last-child {
                color: #3199bd;
            }

            &.active {
                border-color: #3199bd;
                color: #3199bd;
            }
        }
    }

    &>button {
        margin: 14px 14px;
        width: calc(100% - 28px);
        height: 38px;
        min-height: 38px;
    }
}

.detail-downloading {
    &::v-deep .dialog-content {
        border-radius: 28px;

        .dialog-body {
            display: flex;
            flex-direction: column;
            overflow: hidden;
            justify-content: center;
            align-items: center;
            width: 320px;
            height: 320px;
        }
    }

    .el-progress {
        width: 96px;
        height: 96px;

        &::v-deep {
            .el-progress-circle {
                width: 96px;
                height: 96px;
            }

            .el-progress__text {
                font-size: 20px;
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                color: #000000;
            }
        }
    }

    p {
        margin-top: 24px;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;
        line-height: 16px;
    }
}
</style>
